package com.wdt.shirojwt.config.ds;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "baseSysSqlSessionFactory")

public class DataSourceConfig {

    // 精确到 base_sys 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.wdt.shirojwt.dao.test";
    static final String MAPPER_LOCATION = "classpath:mapper/test/*.xml";

    @Value("${base_sys.datasource.url}")
    private String url;

    @Value("${base_sys.datasource.username}")
    private String user;

    @Value("${base_sys.datasource.password}")
    private String password;

    @Value("${base_sys.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "baseSysDataSource")
    @Primary
    public DataSource baseSysDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "baseSysTransactionManager")
    @Primary
    public DataSourceTransactionManager baseSysTransactionManager() {
        return new DataSourceTransactionManager(baseSysDataSource());
    }

    @Bean(name = "baseSysSqlSessionFactory")
    @Primary
    public SqlSessionFactory baseSysSqlSessionFactory(@Qualifier("baseSysDataSource") DataSource baseSysDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(baseSysDataSource);

        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}